package com.fullertontech.framework.global;

import java.lang.annotation.Annotation;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestExecutionListener;

public class GlobalUtils implements TestExecutionListener
{
	//启动类
    private static Class<?> mainClass;
    //启动类包名
    private static String mainClassPackageName;
    
    static {
    	initMainClass();
    }

	public static String getMainClassPackageName() {
		return mainClassPackageName;
	}

	public static Class<?> getMainClass() {
		return mainClass;
	}
	
	public static <A extends Annotation> A getAnnotation(Class<A> classes){
		return mainClass.getAnnotation(classes);
	}
	
	private static synchronized void initMainClass() {
		if(mainClass==null) {
			//获取项目包路径
			StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
			for (StackTraceElement stackTraceElement : stackTrace) {
				if ("main".equals(stackTraceElement.getMethodName())) {
					try {
						mainClass=Class.forName(stackTraceElement.getClassName());
						mainClassPackageName=mainClass.getPackage().getName();
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					}
					break;
				}
			}
		}
	}


	@Override
	public void prepareTestInstance(TestContext testContext) throws Exception {
		try {
			EnableTest enableTest=testContext.getTestClass().getAnnotation(EnableTest.class);
			if(enableTest!=null) {
				mainClass=enableTest.classes();
				mainClassPackageName=mainClass.getPackage().getName();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
